#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>

int main(int argc,const char * argv[])
{
    key_t key;
    int shmid;
    char *p = NULL;
    key = ftok("./app",'a');
    if(key<0)
    {
        perror("ftok err");
        return -1;
    }

    //1创建共享内存
    shmid = shmget(key,128,IPC_CREAT|IPC_EXCL|0666);
    if(shmid<0)
    {
        if(errno == EEXIST)
        shmid = shmget(key,128,0666);
        else
        {
            perror("shmget err");
            return -1;
        } 
    }
    
    //2.映射,将共享内存地址映射到用户空间
    //参数：NULL：让系统自动完成映射，0：可读可写
    p = (char*)shmat(shmid,NULL,0);
    if(p == (char*)-1)
    {
        perror("shmat err");
        return -1;
    }

    fgets(p,32,stdin);
    printf("p:%s",p);
    printf("shmid:%d\n",shmid);
    printf("%#x\n",key);

    //3取消映射
    shmdt(p);
    //4删除共享内存
    shmctl(shmid,IPC_RMID,NULL);
    
    system("ipcs -m");

    return 0;
}